<!-- 一键托管 -->
<template>
  <div class="all">
    
    <scroller class="scroller" v-if="exchanges">
      <div class="wrapper">

        <!--Api-->
        <VCApi class="api" v-if="spotOrContract" v-model="api" :trust="true" :exchanges="exchanges" @apiChange="apiChange()"></VCApi>
        <VApi class="api" v-else v-model="api" :trust="true" :exchanges="exchanges" :type="0" @apiChange="apiChange()"></VApi>

        <!--投入-->
        <VInputUp class="input" v-if="pairMap" ref="input" v-model="investNum" 
          :isMax="true" :investCoin="investCoin" :moneyType="2" :isSlide="false"
          :explain="T('托管金额剔除非USDT的持仓，此部分将进行快照，托管发起方不可操作，您如果操作账户将有可能触发托管结算。')"
          :type="'define'" :name="'其他'" :api="api" 
          :params="[]" :pairMap="pairMap" :limitMap="limitMap"></VInputUp>

        <!--其他设置-->
        <VSet class="set" ref="set" v-model="sets" @open="setOpen"></VSet>

        <!--提示-->
        <div class="tipe bg2">
          <text class="font32 main-t1">{{T('提示')}}</text>
          <text class="font24 text2" >{{T("1、付费方式为固定佣金的，启动后每日自动支付佣金给发起者。")}}</text>
          <text class="font24 text2" >{{T("2、付费方式为盈利分成的，启动时将冻结您的保证金账户，结算时按VTN汇率从保证金中扣除分成金额，支付金额最高不超过保证金全额；退出后保证金解冻。")}}</text>
          <text class="font24 text2" >{{T("3、发起者下架项目即停止支付费用。")}}</text>
          <text class="font24 text2" >{{T("4、您也可以提前退出，终止后即结算费用。")}}</text>
          <text class="font24 text2" >{{T("5、为保证跟单持续执行请确保您的消费账户和保证金账户中拥有足够的VTN；金额不足时将自动终止结算。")}}</text>
          <text class="font24 text2" >{{T("6、包含亏损赔付承诺的，在任意一方退出时结算。")}}</text>
          <text class="font24 text2" >{{T("7、出现API过期或删除、账户资金挪用等情况，亏损赔付承诺自动作废。")}}</text>
          <text class="font24 text2" >{{T(" ")}}</text>
          <text class="font32 udRed-t1">{{T('风险提示')}}</text>
          <text class="font24 text2">{{T('任何交易不能保证其在未来的正盈利性，过往数据不预示未来表现，投资有风险，请谨慎选择。请确保本人完全理解并可以承担相关风险可能带来的结果。')}}</text>
        </div>
      </div>
    </scroller>
    
    <!--启动-->
    <div class="up bg3" v-if="pairMap && api">
      <div class="up-but main1" v-if="api.apiId.length" @click="upClick">
        <text class="font32 text1">{{T('启动')}}</text>
      </div>
      <div class="up-but main1" v-else @click="addClick">
        <text class="font32 text1">{{T('录入API')}}</text>
      </div>
    </div>

    <!--确认弹窗-->
    <div class="ok" v-if="isOk && api">
      
      <div class="flex-1"></div>
      <div class="ok-bg bg3">

        <div class="ok-title">
          <text class="font34 text1">{{T('确认启动')}}</text>
        </div>

        <div class="ok-content">

          <!-- 盈利分成-->
          <template v-if="showStatus == 'online' && profitLayer">
            <text class="font30 text1">{{T('盈利分成')}}</text>
            
            <div class="height30"></div>
            <div v-for="(item, index) in profitLayer.range" v-bind:key="index">
              <div class="row acenter" >
                <text class="font28 text2 all">{{T('盈利>&{1}%的部分').replace("&{1}", item.lowerLimit)}}</text>
                <text class="font28 text1">{{T('分成&{1}%').replace("&{1}", item.proportion)}}</text>
              </div>
              <div class="height30"></div>
            </div>

            <div class="line no1"></div>
            <div class="height30"></div>
            <div class="row acenter">
              <text class="font28 text2 all">{{T('分成上限')}}</text>       
              <text class="font28 text1">{{profitLayer.maxLimit + ' VTN'}}</text>
            </div>
            
            <div class="height30"></div>
            <div class="row acenter">
              <text class="font28 text2 all">{{T('最小可用保证金')}}</text>
              <text class="font28 text1">{{profitLayer.minimumAvailableMargin + ' VTN'}}</text>
            </div>
          </template>

          
          <!-- 亏损赔付 -->
          <template v-if="showStatus == 'online' && riskIndemnityComment">
            <div class="height50"></div>
            <text class="font28 text1">{{T('赔付百分比')}}</text>

            <div class="height30"></div>
            <div v-for="(item, index) in riskIndemnityComment.range" v-bind:key="index">
              <div class="row acenter" >
                <text class="font28 text2 all">{{T('亏损>&{1}%的部分').replace("&{1}", item.lowerLimit)}}</text>
                <text class="font28 text1">{{T('赔付&{1}%').replace("&{1}", item.commentProportion)}}</text>
              </div>
              <div class="height30"></div>
            </div>

            <div class="line no1"></div>
            <div class="height30"></div>
            <div class="row acenter">
              <text class="font28 text2 all">{{T('赔付承诺生效时间')}}</text>        
              <text class="font28 text1">{{riskIndemnityComment.timeEnd}}</text>
            </div>
          </template>

          <div class="height50"></div>
          <text class="font30 text1">{{T('投入金额')+'：'+investNum+' '+investCoin}}</text>
          <div class="height50"></div>
        </div>

        <div class="row">
          <div class="ok-but" @click="isOk = false">
            <text class="font34 main-t1">{{T('取消')}}</text>
          </div>
          <div class="ok-but" @click="httpUp">
            <text class="font34 main-t1">{{T('确认')}}</text>
          </div>
        </div>
      </div>
      <div class="flex-2"></div>
    </div>
  </div>
</template>


<script>

//组件
import VCApi from "@/upContract/view/VCApi.vue";
import VApi from "@/up/view/VApi.vue";
import VInputUp from "@/up/view/VInputUp.vue";
import VSet from "@/up/view/VSet.vue";

//功能
import navigator from "@/_js/navigator";
import config from "@/_js/config";
import math from "@/_js/math";
import modal from "@/_js/modal";
import broadcast from "@/_js/broadcast";
import API from "@/_js/api";
import mParam from "@/up/amParam";
import debug from "@/_js/debug";


const weexFunction = weex.requireModule("WeexFunction");
import weexHttp from "@/_js/https"; ;

import I18N from "@/_i18n/i18n";
var T = I18N.t;
weexFunction.setTitle(T("一键托管"));

export default {

  components: {
    VCApi,
    VApi,
    VInputUp,
    VSet,
  },

  data() {
    return {
      T:T,
      config:config,
      math:math,
      isOk:false, //turn弹出启动确定页
      isTipe:false, //true已弹出过提示弹窗

      teamProjectId:"",//项目编号
      showStatus:undefined, //项目发布状态 notOnline: 下架，online：上架,review：审核中

      api:undefined, //API
      investNum:'0', //投资数量
      moneyNum:'0', //可用数量

      pairMap:undefined, //交易对

      exchanges:undefined, //支持交易所

      spotOrContract:false, //turn全支持、false现货
      investCoin:undefined, //投资币
      limitMap:undefined, //投入限制
      profitLayer:undefined, //盈利分成
      riskIndemnityComment:undefined, //亏损赔付

      sets:{'isOpen':false, //turn 显示
            'isEdit':true, //true 可编辑
            'stopProfit':'', //止盈率
            'stopLoss':'', //止损率
            }
    };
  },

  mounted() {

    this.teamProjectId = navigator.getParam("teamProjectId");

    setTimeout(() => {
      this.httpTrustDetail();
    }, 500);
  },

  methods: {
    
    /********************************** HTTP*/
    //http托管策略详情
    httpTrustDetail() {

      modal.showLoad();
      var param = {'teamProjectId': this.teamProjectId};
      weexHttp.post("foundation/queryFundDetail",param,false,(data) => {
        modal.hideLoad();
        if (data.status == 200) {
          var data = data.data;
          var advanceSetting = data.advanceSetting;

          //turn全支持、false现货
          this.spotOrContract = advanceSetting.spotOrContract.length > 1;

          //发布状态
          this.showStatus = data.showStatus;

          //盈利分成
          this.profitLayer = advanceSetting.profitLayer;

          //亏损赔付
          var riskIndemnityComment = advanceSetting.riskIndemnityComment;

          if (riskIndemnityComment) {
            riskIndemnityComment.timeEnd = this.getEndTime(riskIndemnityComment.effectTime);
            this.riskIndemnityComment = riskIndemnityComment;
          }

          //投资币
          this.investCoin = advanceSetting.symbol; 

          //投入限制
          this.limitMap = {'maxInvest':advanceSetting.max, 'minInvest':advanceSetting.min};
                           
          //支持交易所
          var exchanges = [];
          for (let index = 0; index < advanceSetting.exchangeLimit.length; index++) {
            var exchange = advanceSetting.exchangeLimit[index];
            exchanges.push(exchange.exchangeName);
          }
          this.exchanges = exchanges;
        } else {
          modal.toast(data.msg);
        }
      });
    },

    //http查询币种行情价
    httpsMarketDetail(exchangeName) {

      //无法正确获取保留小数位
      var param = this.investCoin == 'USDT' ? 
                  {'exchangeName': exchangeName,
                    'baseCoin':'USDT', 
                    'counterCoin': 'BTC'}
                  : {'exchangeName': exchangeName,
                    'baseCoin':this.investCoin, 
                    'counterCoin': "USDT"};
      weexHttp.post("quoteV2/queryMarketDetail",param,true,(data) => {
        if (data.status == 200) {
          var pairMap = data.data;
          pairMap['baseCoinDecimal'] = math.getCoin(this.investCoin);
          pairMap['counterCoinDecimal'] = math.getCoin(this.investCoin);
          this.pairMap = pairMap;
        } else {
          modal.toast(data.msg);
        }
      });
    },
    
    //启动
    httpUp() {
      this.isOk = false;
      modal.showLoad();
      var setMap = this.$refs.set.getParam();
      var param = {'teamProjectId': this.teamProjectId, 
                   'exchangeName':this.api.exchangeName,
                   'investCoin':this.investCoin,
                   'investCoinNum':this.investNum,
                   'trustNum':this.investNum //2021.12.11日和胡豪调试接口，投入金额参数变更了，未了避免出错，新增参数补删除原来参数
                   };
      param = Object.assign(param, setMap);
      mParam.getApiParam(this.api, (apiMap)=>{
        param = Object.assign(param, apiMap);
        weexHttp.postX("foundation/fundStart",param,true,(data) => {
          if (data.status == 200) {
            var data = data.data;
            weexFunction.setShowTabBar(1);
            weexFunction.postNotificationName('StrategyShow', {'index':0});
            setTimeout(() => {
              modal.hideLoad();
              var msg =  "您的账户已托管成功，最终托管金额为"+data.investCoinNum+this.investCoin;
              modal.alert(msg, ()=>{
                broadcast.send('UpShow', {'index':1});
                broadcast.send(broadcast.EXECUTE_UPDATE);
                navigator.back(2);
              });
            }, 1000);
          } else if (data.status == 11004) {
            modal.hideLoad();
            var parm = {message:T("很抱歉！由于保证金账户可用余额未达到最小可用保证金要求，执行实例不能启动，您可以前往充值后再来启动。"),
                        okBtn:T("前往转入"), cancelBtn:T("知道了")};
            modal.confirm(parm, (bool)=>{
              var param = {'type':1};
              (bool == "true") && navigator.open('', "wallet/Wallet", param);
            });
          } else {
            modal.hideLoad();
            modal.toast(data.msg);
          }
        });
      });
    },

    /********************************* 其他方法*/
    //获取结束时间
    getEndTime(effectTime) {

      var delayed = math.cheng(effectTime, '86400000', 0, 2);

      var timestamp = new Date().getTime();
      timestamp = timestamp + Number(delayed);

      var time = new Date(Number(timestamp));
      var year = time.getFullYear();

      var month = time.getMonth() + 1;
      month = month < 10 ? "0"+month : month;

      var day = time.getDate();
      day = day < 10 ? "0"+day : day;

      var hour = time.getHours();
      hour = hour < 10 ? "0"+hour : hour;

      var minute = time.getMinutes();
      minute = minute < 10 ? "0"+minute : minute;

      return year+"/"+month+"/"+day + ' ' + hour +":"+ minute;
    },

    //api改变
    apiChange() {
      debug.log('进来了');
      debug.log(this.api);
      this.httpsMarketDetail(this.api.exchangeName)
      if (this.api.apiId == '') {
        this.apiTipe();
      } else {
        this.tipeDialog();
        // API.synchroApi(this.api.apiId);
      }
    },
    
    //进入界面提示弹出
    tipeDialog() {
      if (this.isTipe) return;
      this.isTipe = true;
      var text1 = T('如您的合约账户中拥有持仓或委托，请先手动撤单平仓；');
      var text2 = T('您的币币账户持仓可以选择保留，项目将自动撤销委托并快照资产后进行托管；');
      var text3 = T('如您的账户可托管资金超过项目托管资金上限，将以上限金额进行托管；');
      var text4 = T('托管期间不可进行交易操作，否则将有可能触发托管结算；');
      var text = text1 + '\n' + text2 + '\n' + text3+ '\n' + text4;
      var param = {'title':T('操作提示'), 'text':text, 'no':'', 'yes':T('知道了')};
      navigator.openDialog('_public/TipsAc', param);
    },

    //api提示
    apiTipe() {
      
      var tipe;
      for (let index = 0; index < this.exchanges.length; index++) {
        var exchange = this.exchanges[index];
        tipe = tipe ? (tipe + '、' + exchange) : exchange;
      }


      if (this.spotOrContract) {
        tipe = T("很抱歉，该托管只支持&{1}。请录入对应交易所API，并开放USDT合约交易权限。").replace("&{1}", tipe);
      } else {
        tipe = T("很抱歉，该托管只支持&{1}。请录入对应交易所API。").replace("&{1}", tipe);
      }

      var parm = {message:tipe,
                  okBtn:T("录入API"), cancelBtn:T("取消")};
      modal.confirm(parm, (bool)=>{
        (bool == "true") && this.addClick();
      });
    },
    
    /********************************** 点击触发*/
    //录入APi
    addClick() {
      var nav = {'navColor':'#0c0c0c'};
      navigator.open('', 'home/ApiAdd', undefined, nav);
    },

    //启动
    upClick() {
      //投入资金
      if (this.$refs.input.checkError()) {
        return;
      }
      
      //其他设置
      if (this.$refs.set.checkError()) {
        return;
      }
      
      this.isOk = true;
    },
  },
};
</script>

 
<style src="@/_css/style.css"></style>
<style scoped>
.scroller {
  flex: 1;
}
.wrapper {
  padding-left: 40px;
  padding-right: 40px;
  padding-bottom: 40px;
}
.line {
  height: 1px;
}

.api {
  margin-left: 20px;
  margin-right: 20px;
  margin-top: 40px;
  padding-bottom: 40px;

  background: tomato;
}

.input {
  margin-bottom: 20px;
}

.set {
  margin-top: 30px;
  margin-bottom: 40px;
}

.tipe {
  border-radius: 24px;

  padding: 20px;

  margin-left: -20px;
  margin-right: -20px;
}

.up{
  flex-direction: column;
  height: 164px;

  padding-left: 40px;
  padding-right: 40px;
}
.up-but{
  flex-direction: row;
  justify-content: center;
  align-items: center;
  height: 80px;
  border-radius: 4px;

  margin-top: 28px;
}

/*************** 确定弹窗*/
.ok{
  position: absolute;
  flex-direction: column;
  align-items: center;
  z-index: 9;
  top:0;
  right: 0;
  bottom:0;
  left:0;
  background-color:rgba(0,0,0,0.6);
}
.ok-bg{
  width:600px;
  border-radius:24px;
}
.ok-title {
  align-items: center;
  margin-top: 50px;
  margin-bottom: 50px;
}
.ok-content{
  padding-left: 40px;
  padding-right: 40px;
}
.ok-but {
  justify-content: center;
  align-items: center;
  flex: 1;
  height: 120;
}

/*************** 间距*/
.height30 {
  height: 30px;
}
.height50 {
  height: 50px;
}
.flex-1 {
  flex: 1;
}
.flex-2 {
  flex: 2;
}
</style>
